"use client"

import type React from "react"

import { useState } from "react"
import Image from "next/image"
import { Play, Pause, Heart } from "lucide-react"
import { cn } from "@/lib/utils"
import { toggleFavorite } from "@/lib/api-client"
import { formatDuration } from "@/lib/format"
import { MoreOptionsMenu } from "@/components/more-options-menu"
import type { Song } from "@/types/song"
import Link from "next/link"
import { Button } from "@/components/ui/button"

interface SongCardProps {
  song: Song
  index: number
  showAlbum?: boolean
  onSongUpdated?: (updatedSong: Song) => void
  userId?: number
  onPlay?: (songId: number) => void
  isPlaying?: boolean
  className?: string
}

export function SongCard({ song, userId, onPlay, isPlaying = false, className }: SongCardProps) {
  const [isLiked, setIsLiked] = useState(song.isLiked || false)
  const [isLoading, setIsLoading] = useState(false)

  const handleLikeToggle = async (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()

    if (!userId) {
      window.location.href = "/login"
      return
    }

    setIsLoading(true)

    try {
      await toggleFavorite({
        contentType: "song",
        contentId: song.id,
        userId: userId,
        action: !isLiked,
      })
      setIsLiked(!isLiked)
    } catch (error) {
      console.error("收藏/取消收藏歌曲失败:", error)
    } finally {
      setIsLoading(false)
    }
  }

  const handlePlay = (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    if (onPlay) {
      onPlay(song.id)
    }
  }

  return (
      <div
          className={cn(
              "group flex items-center p-2 rounded-md hover:bg-gray-100 transition-colors cursor-pointer",
              isPlaying && "bg-gray-100",
              className,
          )}
          onClick={handlePlay}
      >
        <div className="flex items-center gap-3 flex-1 min-w-0">
          <div className="relative w-10 h-10 flex-shrink-0">
            <Image
                src={song.cover || "/placeholder.svg?height=40&width=40"}
                alt={song.title}
                fill
                className="object-cover rounded"
            />
            <div className="absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity rounded">
              <Button variant="ghost" size="icon" className="h-8 w-8 text-white" onClick={handlePlay}>
                {isPlaying ? <Pause className="h-5 w-5" /> : <Play className="h-5 w-5" />}
              </Button>
            </div>
          </div>

          <div className="flex-1 min-w-0">
            <div className="font-medium truncate">{song.title}</div>
            <div className="text-sm text-muted-foreground truncate">{song.artists}</div>
          </div>
        </div>

        {song.album && (
            <div className="hidden md:block flex-shrink-0 mx-4 max-w-[200px]">
              <Link
                  href={`/album/${song.album.id}`}
                  className="text-sm text-muted-foreground truncate hover:text-primary transition-colors"
                  onClick={(e) => e.stopPropagation()}
              >
                {song.album.title}
              </Link>
            </div>
        )}

        {/* Release date */}
        <div className="hidden md:block text-sm text-muted-foreground flex-shrink-0 mx-4">{song.releaseDate}</div>
        <div className="flex items-center gap-1">
          <span className="text-sm text-muted-foreground mr-2">{formatDuration(song.duration)}</span>

          <Button
              variant="ghost"
              size="icon"
              className={cn("h-8 w-8", isLiked && "text-red-500")}
              onClick={handleLikeToggle}
          >
            <Heart className={cn("h-4 w-4", isLiked && "fill-current")} />
          </Button>

          <MoreOptionsMenu
              resource={{
                id: song.id,
                type: "song",
                title: song.title,
                cover: song.cover,
                artist: song.artists,
              }}
              onAddToPlaylist={() => {
                console.log("Add to playlist:", song.title)
              }}
              onDownload={() => {
                console.log("Download:", song.title)
              }}
              align="end"
              side="left"
              className="h-8 w-8"
          />
        </div>
      </div>
  )
}

